package com.jt.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
    /**
     * 获取Cookie对象
     * @param request 请求对象
     * @param cookieName 要查找的Cookie名字
     * @return Cookie对象
     */
    public static Cookie getCookie(HttpServletRequest request, String cookieName){
        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0){
            for (Cookie cookie:cookies){
                if (cookieName.equals(cookie.getName())){
                    return cookie;
                }
            }
        }
        return null;
    }

    /**
     * 获取Cookie的值
     * @param request 请求对象
     * @param cookieName Cookie的名字
     * @return 返回Cookie的值
     */
    public static String getCookieValue(HttpServletRequest request,String cookieName){
        Cookie cookie = getCookie(request, cookieName);
        return cookie==null?null:cookie.getValue();
    }

    /**
     * 新增/删除Cookie
     * @param response 响应对象
     * @param cookieName Cookie名字
     * @param cookieValue Cookie值
     * @param path 路径
     * @param domain 共享
     * @param seconds 超时时间
     */
    public static void addCookie(HttpServletResponse response,String cookieName,String cookieValue,String path,String domain,Integer seconds){
        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setPath(path);
        cookie.setDomain(domain);
        cookie.setMaxAge(seconds);
        response.addCookie(cookie);
    }
}
